<template>
  <div class="page-container">
    <div class="mt-3"></div>
    <Statictop title="库存统计" type="amount2" :storeList="sitIdamount.amount2.siteList" @onchange="onchange" />
    <a-row :gutter="[20, 10]">
      <a-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
        <a-skeleton-shape v-if="!sitIdamount.amount2.status" style="height: 240px; width: 100%" />
        <div v-else>
          <headertit title="门店库存统计" :data="sitIdamount.amount2.siteId ? '' : '点击柱状图查看对应门店车型数量'">
            <template #tipcontent>
              <div> 柱状图中的分子、分母说明 </div>
              <div> Y / X：出库车辆数 / 车辆总数 </div>
              <div> Y：租赁中+运维中+已借出的车辆 </div>
              <div> X：门店下的全部车辆数，不计算已处置、已归还的车辆 </div>
            </template>
            <template #amountNum>
              <div v-if="sitIdamount.amount2.siteId" class="chart-radio-group flex">
                <div
                  v-for="(tab, index) in tabs"
                  :key="tab.name"
                  class="chart-radio flex justify-center items-center px-2 h-5"
                  :class="{ 'chart-active': index === isCurrent }"
                  @click="onClickCar(tab.type, index)"
                >
                  {{ tab.name }}
                </div>
              </div>
            </template>
          </headertit>
          <storepiechart
            v-if="sitIdamount.amount2.siteId"
            :carStatisticsamount="storepiechartData"
            :data="sitIdamount.amount2.data.carCountDto && sitIdamount.amount2.data.carCountDto[0]"
          />
          <StoreInventory v-else :carStatisticsamount="sitIdamount.amount2.data" />
        </div>
      </a-col>
      <a-col :xs="1" :sm="1" :md="1" :lg="1" :xl="1" />
      <a-col :xs="11" :sm="11" :md="11" :lg="11" :xl="11">
        <a-skeleton-shape v-if="!sitIdamount.amount2.status" style="height: 240px; width: 100%" />
        <div v-else>
          <headertit title="车辆占用率">
            <template #amountNum>
              <div class="car-num">车辆总数：{{ sitIdamount.amount2.data.totalCount }} 辆 </div>
            </template>
          </headertit>
          <CarRate
            :carStatisticsamount="sitIdamount.amount2.data"
            :siteId="sitIdamount.amount2.siteId"
            :siteName="sitIdamount.amount2.siteName"
            style="cursor: pointer"
          />
        </div>
      </a-col>
    </a-row>
    <a-divider class="panel-border" />

    <Statictop
      title="车辆出租率统计"
      data="非实时数据，每间隔4小时进行一次数据更新"
      type="amount3"
      :storeList="sitIdamount.amount3.siteList"
      @onchange="onchange"
      @onchangeTime="onchangeTime"
      :timeList="time[2]"
      :timeValue="1"
      showTime
    />
    <a-row>
      <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <headertit title="出租率" content="出租率=出租租日/总租日 * 100%" />
        <a-skeleton-shape v-if="!sitIdamount.amount3.status" style="height: 180px; width: 100%" />
        <HireRatechart v-else :carUseRatelistamount="sitIdamount.amount3.data" :amount="sitIdamount.amount3" title="出租率" />
      </a-col>
    </a-row>
    <a-divider class="panel-border" />

    <Statictop title="门店预计收益" type="amount4" :storeList="sitIdamount.amount4.siteList" @onchange="onchange" />
    <a-row>
      <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <headertit title="自驾短租未来30天预计收益(含当天)" content="仅计算订单的车辆租金" />
        <a-skeleton-shape v-if="!sitIdamount.amount4.status" style="height: 240px; width: 100%" />
        <HireRatechart v-else :carUseRatelistamount="sitIdamount.amount4.data" :amount="sitIdamount.amount4" title="自驾短租" />
      </a-col>
    </a-row>
    <a-divider class="panel-border" />

    <Statictop
      title="订单收益统计"
      type="amount5"
      :storeList="sitIdamount.amount5.siteList"
      @onchange="onchange"
      :timeList="time[1]"
      @onchangeTime="onchangeTime"
      @onChangeChannel="onChangeChannel"
      showTime
      showChannel
    />
    <a-row>
      <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <headertit title="自驾短租收益趋势" content="仅计算订单账单中已确认的费用作为收益，不计算已作废的订单账单费用" />
        <a-skeleton-shape v-if="!sitIdamount.amount5.status" style="height: 380px; width: 100%" />
        <OrderRevenuechart v-else chartId="orderrevenue" title="自驾短租收益趋势" :orderRevenueamount="sitIdamount.amount5.data" />
      </a-col>
    </a-row>
    <a-divider class="panel-border" />

    <Statictop
      title="订单量统计"
      type="amount6"
      :storeList="sitIdamount.amount6.siteList"
      @onchange="onchange"
      :timeList="time[1]"
      @onchangeTime="onchangeTime"
      @onChangeChannel="onChangeChannel"
      showTime
      showChannel
    />
    <a-row>
      <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <headertit title="自驾短租订单量趋势" content="不计算已取消、已作废的订单，以下单日期统计订单量" />
        <a-skeleton-shape v-if="!sitIdamount.amount6.status" style="height: 380px; width: 100%" />
        <OrderRevenuechart v-else chartId="ordernum" title="自驾短租订单量趋势" :orderRevenueamount="sitIdamount.amount6.data" />
      </a-col>
    </a-row>

    <a-divider />

    <div class="flex flex-wrap justify-between">
      <div class="mb-3 text-base font-semibold">车系/车型收益排行</div>
      <summary-nav-filter ref="summaryNavFilterRef" @change="filterChange" :tableType="tableType">
        <template v-if="tableType == 'carSeries'">
          <remote-select
            v-model="orderRevenueQueryParam.seriesIdList"
            :max-tag-count="1"
            type="car_series_multiple"
            style="width: 220px"
            placeholder="全部车系"
            @visible-change="(e: any) => handlePopupVisibleChange(e, 0)"
          />
        </template>
        <template v-else>
          <remote-select
            v-model="orderRevenueQueryParam.modelIdList"
            :max-tag-count="1"
            type="car_model_multiple"
            style="width: 220px"
            placeholder="全部车型"
            @visible-change="(e: any) => handlePopupVisibleChange(e, 1)"
          />
        </template>
      </summary-nav-filter>
    </div>

    <div class="chart-radio-group flex mb-4">
      <div
        v-for="tab in tabs1"
        :key="tab.name"
        class="chart-radio flex justify-center items-center py-1 px-4 h-8"
        :class="{ 'chart-active': tableType == tab.type }"
        @click="onClickCar2(tab.type)"
      >
        {{ tab.name }}
      </div>
    </div>
    <OrderRevenuetable ref="orderRevenuetableRef" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted } from 'vue'
  import { carStockStatistics, carUseRatelist, selectStoreRevenue, orderRevenuelist, orderCountlist } from '@/api/databoard.js'

  import headertit from './components/databoard/components/Headertit.vue'
  import CarRate from './components/databoard/CarRatechart.vue'
  import Statictop from './components/databoard/components/Statictop.vue'
  import StoreInventory from './components/databoard/StoreInventorychart.vue'
  import storepiechart from './components/databoard/storepiechart.vue'
  import HireRatechart from './components/databoard/HireRatechart.vue'
  import OrderRevenuechart from './components/databoard/OrderRevenuechart.vue'
  import summaryNavFilter from './revenue-summary/components/summary-nav-filter.vue'
  import OrderRevenuetable from './revenue-summary/components/OrderRevenuetable.vue'
  import { debounce } from 'lodash-es'

  export default defineComponent({
    name: 'DataBoard',
    components: {
      headertit,
      Statictop,
      StoreInventory,
      storepiechart,
      CarRate,
      HireRatechart,
      OrderRevenuechart,
      summaryNavFilter,
      OrderRevenuetable,
    },
    setup() {
      const isCurrent = ref(0)
      const tabs = [
        {
          type: 'series',
          name: '车系维度统计',
        },
        {
          type: 'model',
          name: '车型维度统计',
        },
      ]
      const time = ref([
        [
          { label: '本周', value: 1 },
          { label: '上周', value: 5 },
          { label: '本月', value: 2 },
          { label: '上月', value: 6 },
          { label: '本季度', value: 3 },
          { label: '上季度', value: 7 },
          { label: '本年', value: 4 },
          { label: '去年', value: 8 },
        ],
        [
          { label: '近1周', value: 1 },
          { label: '近1个月', value: 2 },
          { label: '近1年', value: 3 },
        ],
        [
          { label: '前后15天', value: 1 },
          { label: '近1年', value: 2 },
        ],
      ])
      const sitIdamount = ref<any>({
        amount2: { siteId: '', siteName: '全部门店', name: '库存统计', data: [], status: false, siteList: [] },
        amount3: { siteId: '', siteName: '全部门店', time: 1, name: '车辆出租率统计', data: [], status: false, siteList: [] },
        amount4: { siteId: '', siteName: '全部门店', name: '门店预计收益', data: [], status: false, siteList: [] },
        amount5: { siteId: '', siteName: '全部门店', channelType: '', time: 2, name: '订单收益统计', status: false, siteList: [] },
        amount6: { siteId: '', siteName: '全部门店', channelType: '', time: 2, name: '订单量统计', data: [], status: false, siteList: [] },
      })

      // 车系/车型收益排行 ================================================
      const tabs1 = [
        {
          type: 'carSeries',
          name: '按车系排行',
        },
        {
          type: 'carModel',
          name: '按车型排行',
        },
      ]
      const orderRevenueQueryParam = ref<any>({
        // orderByType: 1 收益 2 订单量
        orderByType: 1,
      })
      const tableType = ref('carSeries')
      const orderRevenuetableRef = ref<any>()

      const handleOrderRevenuetableRef = (params: any, operateType?: any) => {
        if (orderRevenuetableRef.value) {
          orderRevenuetableRef.value.loadData({ ...params, tableType: tableType.value }, operateType)
        }
      }

      // 车系/车型收益排行筛选
      const filterChange = (val: any) => {
        orderRevenueQueryParam.value = {
          ...orderRevenueQueryParam.value,
          siteIdList: val.siteIdList,
          orderTimeQueryType: val.orderTimeQueryType,
          startTime: val.startTime,
          endTime: val.endTime,
          seriesIdList: val.seriesIdList,
        }

        handleOrderRevenuetableRef(orderRevenueQueryParam.value)
      }

      // 增加防抖
      const handlePopupVisibleChange = debounce((e: any, index: number) => {
        const params = {
          ...orderRevenueQueryParam.value,
          [index == 0 ? 'seriesIdList' : 'modelIdList']: orderRevenueQueryParam.value[index == 0 ? 'seriesIdList' : 'modelIdList'],
        }
        handleOrderRevenuetableRef(params)
      }, 600)

      const onClickCar2 = (type: string) => {
        tableType.value = type
        if (type == 'carSeries') {
          orderRevenueQueryParam.value.modelIdList = null
        } else if (type == 'carModel') {
          orderRevenueQueryParam.value.seriesIdList = null
        }
        handleOrderRevenuetableRef(orderRevenueQueryParam.value, 'tableTypeChange')
      }
      // 车系/车型收益排行 ================================================

      // 门店库存统计饼状图切换
      const storepiechartData = ref<any[]>([])
      const onClickCar = (type: string, index: number) => {
        console.log('type', type, index)
        if (type === 'series') {
          storepiechartData.value = sitIdamount.value.amount2.data.carCountDto[0].carSeriesInfoDto
        } else {
          storepiechartData.value = sitIdamount.value.amount2.data.carCountDto[0].carModelInfoDto
        }
        isCurrent.value = index
      }
      // 车辆库存统计
      function rendercarStatistics() {
        carStockStatistics({
          siteId: sitIdamount.value.amount2.siteId,
        }).then((res) => {
          if (res.code === 200) {
            sitIdamount.value.amount2.data = res.result
            res.result?.carCountDto[0].carSeriesInfoDto.forEach((item: any) => {
              item.tmpName = item.seriesName
            })
            res.result?.carCountDto[0].carModelInfoDto.forEach((item: any) => {
              item.tmpName = item.modelName
            })
            storepiechartData.value = res.result.carCountDto[0].carSeriesInfoDto
            sitIdamount.value.amount2.status = true
          }
        })
      }
      //车辆出租率统计
      function rendercarUseRatelist() {
        carUseRatelist({
          siteId: sitIdamount.value.amount3.siteId,
          carRateTimeType: sitIdamount.value.amount3.time,
        }).then((res) => {
          if (res.code === 200) {
            sitIdamount.value.amount3.data = res.result
            sitIdamount.value.amount3.status = true
          }
        })
      }
      //门店预计收益
      function renderexpectRevenuelist() {
        selectStoreRevenue({
          siteId: sitIdamount.value.amount4.siteId,
        }).then((res) => {
          if (res.code === 200) {
            sitIdamount.value.amount4.data = res.result.shortOrder
            sitIdamount.value.amount4.status = true
          }
        })
      }

      // 门店筛选
      function onchange(id, val, name) {
        console.log('onchange', id, val, name)
        sitIdamount.value[id].siteId = val
        sitIdamount.value[id].siteName = name
        if (id === 'amount2') {
          sitIdamount.value[id].data = []
          isCurrent.value = 0
          rendercarStatistics()
        } else if (id === 'amount3') {
          rendercarUseRatelist()
        } else if (id === 'amount4') {
          renderexpectRevenuelist()
        } else if (id === 'amount5') {
          renderorderRevenue()
        } else if (id === 'amount6') {
          renderorderCountlist()
        }
      }
      // 时间筛选
      function onchangeTime(id, val) {
        sitIdamount.value[id].time = val
        if (id === 'amount3') {
          rendercarUseRatelist()
        } else if (id === 'amount5') {
          renderorderRevenue()
        } else if (id === 'amount6') {
          renderorderCountlist()
        }
      }
      // 渠道筛选
      function onChangeChannel(id, val, name) {
        console.log('onChangeChannel', id, val, name)
        sitIdamount.value[id].channelType = val ?? ''
        if (id == 'amount5') {
          renderorderRevenue()
        } else if (id == 'amount6') {
          renderorderCountlist()
        }
      }

      //订单收益统计
      const OrderRevenueData = ref<any[]>([])
      function renderorderRevenue() {
        orderRevenuelist({
          siteId: sitIdamount.value.amount5.siteId,
          incomeDateType: sitIdamount.value.amount5.time,
          channelType: sitIdamount.value.amount5.channelType,
        }).then((res) => {
          if (res.code === 200) {
            sitIdamount.value.amount5.data = res.result
            res.result.series.forEach((item: any) => {
              item.tmpName = item.seriesName
            })
            OrderRevenueData.value = res.result.series
            sitIdamount.value.amount5.status = true
          }
        })
      }

      //订单量统计
      const orderTotalData = ref<any[]>([])
      function renderorderCountlist() {
        orderCountlist({
          siteId: sitIdamount.value.amount6.siteId,
          incomeDateType: sitIdamount.value.amount6.time,
          channelType: sitIdamount.value.amount6.channelType,
        }).then((res) => {
          if (res.code === 200) {
            sitIdamount.value.amount6.data = res.result
            res.result.series.forEach((item: any) => {
              item.tmpName = item.seriesName
            })
            orderTotalData.value = res.result.series
            sitIdamount.value.amount6.status = true
          }
        })
      }

      onMounted(() => {
        rendercarStatistics()
        rendercarUseRatelist()
        renderexpectRevenuelist()
        renderorderRevenue()
        renderorderCountlist()
      })
      return {
        isCurrent,
        tabs,
        tabs1,
        time,
        storepiechartData,
        OrderRevenueData,
        orderTotalData,
        rendercarUseRatelist,
        rendercarStatistics,
        renderexpectRevenuelist,
        renderorderRevenue,
        renderorderCountlist,
        onchange,
        sitIdamount,
        orderRevenuetableRef,
        orderRevenueQueryParam,
        tableType,
        handlePopupVisibleChange,
        onClickCar2,
        filterChange,
        onchangeTime,
        onChangeChannel,
        onClickCar,
      }
    },
  })
</script>

<style lang="less" scoped>
  .car-num {
    font-size: 14px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #1890ff;
    line-height: 20px;
  }

  .chart-radio-group {
    margin-top: 8px;
    .chart-radio {
      font-weight: 400;
      font-size: 12px;
      color: #1890ff;
      border-radius: 999px 999px 999px 999px;
      border: 1px solid #1890ff;
      cursor: pointer;
      margin-right: 16px;

      &.chart-active {
        background-color: #1890ff;
        color: #fff;
      }
    }
  }
</style>

<style lang="less">
  /* 全局echarts tooltip */
  .echarts-tooltip-diy {
    width: auto;
    background: linear-gradient(304.17deg, rgba(253, 254, 255, 0.6) -6.04%, rgba(244, 247, 252, 0.6) 85.2%) !important;
    border: none !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 6px !important;
    pointer-events: auto !important;
    .tooltip-pie {
      white-space: normal;
      word-wrap: break-word;
      font-size: 12px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #1e1e1e;
      line-height: 20px;
    }
    .tooltip-pie-value {
      font-size: 12px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: #4e5969;
      line-height: 20px;
    }

    .whitespace {
      display: block;
      width: 260px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      position: relative;
      margin-right: 20px;
      text-align: left;
    }

    .content-panel {
      display: flex;
      justify-content: space-between;
      padding: 0 9px;
      background: rgba(255, 255, 255, 0.8);
      width: 260px;
      height: 32px;
      line-height: 32px;
      box-shadow: 6px 0px 20px rgba(34, 87, 188, 0.1);
      border-radius: 4px;
      margin-bottom: 4px;
      .tooltip-value {
        font-size: 13px;
        line-height: 15px;
        display: flex;
        align-items: center;
        text-align: right;
        font-family: PingFang SC-Medium, PingFang SC;
        font-weight: 500;
        color: #1d2129;
      }
      .circle {
        display: inline-block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        margin-right: 8px;
      }
    }
    .tooltip-title {
      margin: 0 0 10px 0;
      font-size: 13px;
      line-height: 15px;
      display: flex;
      align-items: center;
      text-align: right;
      font-weight: 500;
      color: #1d2129;
    }
    .flexable {
      width: 260px;
      display: flex;
      justify-content: space-between;
    }
    p {
      margin: 0;
    }
    .tooltip-item-icon {
      display: inline-block;
      margin-right: 8px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
  }
</style>
